from typing import Optional
from fastapi import APIRouter, Header, Query, Body
from fastapi.responses import JSONResponse
from utils.password_utils import get_user_id_from_jwt
from db.operations import UserBookshelfOperations, UserBookshelfQuery
from model.message_model import Message
from model.book_model import Book, BookListResponse
from model.bookshelf_model import BookshelfInsert, BookshelfRemove, BookshelfAddRequest


# 创建书架相关的子路由
router = APIRouter(
    prefix="/bookshelf",
    tags=["bookshelf"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="书架管理接口信息")
async def get_bookshelf_info():
    """获取书架管理接口信息和使用示例"""
    api_info = {
        "message": "书架管理API接口",
        "endpoints": {
            "GET /api/bookshelf/": "获取书架管理接口信息",
            "POST /api/bookshelf/add": "把图书加入书架",
            "DELETE /api/bookshelf/remove": "从书架移除图书",
            "GET /api/bookshelf/list": "获取用户书架列表",
            "GET /api/bookshelf/search": "在书架中搜索图书",
        },
        "examples": {
            "加入书架": {
                "url": "/api/bookshelf/add",
                "method": "POST",
                "header": "Bearer token",
                "body": {"book_id": 123},
                "description": "把图书ID为123的图书加入书架",
            },
            "移除书架": {
                "url": "/api/bookshelf/remove?book_id=123",
                "method": "DELETE",
                "header": "Bearer token",
                "description": "从书架移除图书ID为123的图书",
            },
            "获取书架列表": {
                "url": "/api/bookshelf/list?page=1&limit=10",
                "method": "GET",
                "header": "Bearer token",
                "description": "获取第1页，每页10本书的书架列表",
            },
            "搜索书架": {
                "url": "/api/bookshelf/search?q=python编程&page=1&limit=10",
                "method": "GET",
                "header": "Bearer token",
                "description": "在书架中搜索包含'python编程'关键字的图书",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


# 加入书架
@router.post("/add", summary="把图书加入书架")
async def add_book_to_bookshelf(
    request: BookshelfAddRequest = Body(..., description="图书信息"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """把图书加入书架"""
    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 把图书加入书架的逻辑
        user_bookshelf_ops = UserBookshelfOperations()
        bookshelf_data = BookshelfInsert(
            user_id=user_id,
            book_id=request.book_id,
        ).model_dump()

        result = await user_bookshelf_ops.batch_insert_bookshelf_items([bookshelf_data])
        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="图书已存在于书架中",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="成功加入书架",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"添加失败: {str(e)}",
            ).model_dump(),
        )


# 移除书架
@router.delete("/remove", summary="从书架移除图书")
async def remove_book_from_bookshelf(
    book_id: int = Query(..., description="图书ID"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """从书架移除图书"""
    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )
    if not book_id:
        return JSONResponse(
            status_code=400,
            content=Message(
                message="图书ID不能为空",
            ).model_dump(),
        )

    try:
        # 从书架移除的逻辑
        user_bookshelf_ops = UserBookshelfOperations()
        user_book_pairs = BookshelfRemove(
            user_id=user_id,
            book_id=book_id,
        ).model_dump()
        result = await user_bookshelf_ops.batch_delete_bookshelf_items(
            [user_book_pairs]
        )
        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="图书不在书架中",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="成功从书架移除图书",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"移除失败: {str(e)}",
            ).model_dump(),
        )


# 获取书架列表
@router.get("/list", summary="获取用户书架列表")
async def get_bookshelf_list(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=30, description="每页数量"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """获取用户书架列表"""
    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 现获取书架列表的逻辑
        user_bookshelf_query = UserBookshelfQuery()
        total, books_list = (
            await user_bookshelf_query.query_user_bookshelf_with_pagination(
                user_id=user_id, page=page, limit=limit
            )
        )
        if total == 0 and not books_list:
            return JSONResponse(
                status_code=200,
                content=BookListResponse(
                    message="书架为空",
                    books_list=[],
                    page=page,
                    limit=limit,
                    total=0,
                ).model_dump(),
            )

        books_list = [Book(**book) for book in books_list]

        return JSONResponse(
            status_code=200,
            content=BookListResponse(
                message="获取书架列表成功",
                books_list=books_list,
                page=page,
                limit=limit,
                total=total,
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=BookListResponse(
                message=f"获取书架列表失败: {str(e)}",
                books_list=[],
                page=page,
                limit=limit,
                total=0,
            ).model_dump(),
        )


# 搜索书架
@router.get("/search", summary="在书架中搜索图书")
async def search_bookshelf(
    q: str = Query(..., description="搜索关键字"),
    page: int = Query(1, ge=1, description="页码，从1开始"),
    limit: int = Query(10, ge=1, le=50, description="每页数量，最大50"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """
    在用户书架中搜索图书，支持多字段模糊搜索
    与书城搜索功能保持一致，但限定范围为用户书架
    """
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 搜索书架
        user_bookshelf_query = UserBookshelfQuery()
        total, books_list = await user_bookshelf_query.search_user_bookshelf_by_keyword(
            user_id=user_id,
            keyword=q,
            page=page,
            limit=limit,
        )

        books_list = [Book(**book) for book in books_list]

        return JSONResponse(
            status_code=200,
            content=BookListResponse(
                message="搜索书架成功",
                books_list=books_list,
                total=total,
                page=page,
                limit=limit,
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=BookListResponse(
                message=f"搜索书架失败: {str(e)}",
                books_list=[],
                total=0,
                page=page,
                limit=limit,
            ).model_dump(),
        )
